package user

import (
	"context"

	"mall/common/globalkey"
	"mall/common/mqueuex"
	"mall/common/resultx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserTaskStatisticLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserTaskStatisticLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserTaskStatisticLogic {
	return &GetUserTaskStatisticLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetUserTaskStatisticLogic) GetUserTaskStatistic(in *user.CurrentUserReq) (*user.UserTaskStatisticInfo, error) {
	if in.UserId == nil || *in.UserId == 0 {
		return nil, resultx.StatusError(resultx.USER_ID_REQUIRED, "")
	}

	res, err := l.svcCtx.CurrentUser.FindOne(l.ctx, *in.UserId)
	if err != nil {
		return nil, err
	}

	accountFilterMap := make(map[string]map[string][]any)
	accountFilterMap[model.UserAccountColumns.UserID] = map[string][]any{
		"equalTo": []any{res.ID},
	}
	accountList, _, err := l.svcCtx.CurrentUser.GetAccountList(l.ctx, model.M{
		"pageSize": uint64(1),
	}, -1, accountFilterMap)
	if err != nil || len(accountList) == 0 {
		return nil, err
	}

	account := accountList[0]

	var userTaskStatisticMap map[string]uint32
	statisticFilterMap := make(map[string]map[string][]any)
	statisticFilterMap[model.UserTaskLogColumns.UserID] = map[string][]any{
		"equalTo": []any{res.ID},
	}
	statisticFilterMap[model.UserTaskLogColumns.Status] = map[string][]any{
		"equalTo": []any{globalkey.StatusEnabled},
	}
	statisticList, _, err := l.svcCtx.CurrentUser.GetTaskLogList(l.ctx, model.M{
		"statistic": "1",
	}, -1, statisticFilterMap)
	if err != nil {
		return nil, err
	}

	if len(statisticList) > 0 {
		userTaskStatisticMap = make(map[string]uint32)
		for _, v := range statisticList {
			var slug string
			if v.TaskSlug == mqueuex.UserTaskForumAnswer { // 将回答纳入问题的统计，即问答作为整体进行统计
				slug = mqueuex.UserTaskForumQuestion
			} else {
				slug = v.TaskSlug
			}

			if _, ok := userTaskStatisticMap[slug]; !ok {
				userTaskStatisticMap[slug] = uint32(v.Growth)
			} else {
				userTaskStatisticMap[slug] += uint32(v.Growth)
			}
		}
	}

	return &user.UserTaskStatisticInfo{
		Level:                pointy.GetPointer(uint32(account.Level)),
		UserTaskStatisticMap: userTaskStatisticMap,
	}, nil
}
